import datetime
import pytz

import coin.exchange.base.kr_rest.public_client_base as pubcb
import coin.exchange.bitbank.kr_rest.native_public_client as npubc
from coin.exchange.bitbank.kr_rest.constants import (PERIOD_MAP,
                                                     YYYY_FORMAT_PERIOD,
                                                     YMD_FORMAT_PERIOD)
from coin.exchange.kr_rest.product.product_impl import generate_product_from_str2
from coin.proto.coin_market_query_pb2 import (
    ProductKline,
    ProductKlineElement)


class BitbankFeedParser(object):
  @staticmethod
  def parse_native_kline(update_msg, product, kline_period, start_time, end_time):
   
    assert update_msg['success'] == 1
    klines = update_msg['data']['candlestick'][0]["ohlcv"]
    kline_group = []
    for kline in klines:
      kline_timestamp = kline[5]
      if kline_timestamp / 10**3 >= start_time.timestamp() and \
         kline_timestamp / 10**3 < end_time.timestamp():
        turnover = float(float(kline[4]) * float(kline[3]))
        product_kline = ProductKlineElement(kline_timestamp=int(kline_timestamp * 1e+6),
                                            open=float(kline[0]),
                                            high=float(kline[1]),
                                            low=float(kline[2]),
                                            close=float(kline[3]),
                                            volume=float(kline[4]),
                                            turnover=turnover)
        kline_group.append(product_kline)
    assert len(kline_group) > 0
    kline_period = PERIOD_MAP[kline_period]
    return ProductKline(
        symbol=product.symbol,
        native_symbol=product.native_symbol,
        exchange='Bitbank',
        market_type='Spot',
        kline_period=kline_period,
        klines=kline_group,
    )

class BitbankPublicClient(pubcb.PublicClientBase):
  def __init__(self):
    self.npubc = npubc.BitbankNativePublicClient()

  def query_history_kline_impl(self, product, kline_period, start_time, end_time):
    native_symbol = product.native_symbol
    start_time = start_time.replace(tzinfo=pytz.UTC)
    end_time = end_time.replace(tzinfo=pytz.UTC)
    if kline_period in YYYY_FORMAT_PERIOD:
      time = start_time.strftime("%Y")
    elif kline_period in YMD_FORMAT_PERIOD:
      time = start_time.strftime("%Y") + start_time.strftime("%m") + start_time.strftime("%d")
    else:
      raise ValueError('Unknown query kline period %s', kline_period)
    update = self.npubc.get_history_kline(
        native_symbol, kline_period, time)
    update.msg = BitbankFeedParser.parse_native_kline(update.msg,
                                                  product,
                                                  kline_period,
                                                  start_time,
                                                  end_time)
    
    return update

  def query_level_book_impl(self, product):
    raise NotImplementedError("Bitbank query level book Not Implemented")


if __name__ == "__main__":
  client = BitbankPublicClient()
  start_time = datetime.datetime(2021, 7, 12).replace(tzinfo=pytz.UTC)
  end_time = datetime.datetime(2021, 7, 12, 1, 59, 59).replace(tzinfo=pytz.UTC)
  print(client.query_history_kline(generate_product_from_str2('Spot', 'Bitbank', 'v1', 'BTC-JPY'), '1hour', start_time, end_time).msg)

